<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>学生管理</el-breadcrumb-item>
            <el-breadcrumb-item>学生列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-form :inline="true" :model="studentForm" >
                <el-form-item label="学生姓名" >
                    <el-input v-model="studentForm.sname" placeholder="学生姓名"/>
                </el-form-item>
                <el-form-item label="学生住址">
                    <el-input v-model="studentForm.addr" placeholder="学生住址"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search" size="medium" icon="el-icon-search">查询</el-button>
                    <el-button type="warning" @click="addStudent" size="medium" icon="el-icon-plus" >添加</el-button>
                </el-form-item>
            </el-form>
            <el-table
                    :data="tableData"
                    style="width: 100%">
                <el-table-column
                        label="学号"
                        align="center"
                        width="180"
                        prop="sid">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        align="center"
                        prop="sname"
                        width="180">
                </el-table-column>
                <el-table-column
                        label="性别"
                        prop="sex"
                        align="center"
                        width="100">
                </el-table-column>
                <el-table-column
                        label="年龄"
                        align="center"
                        prop="age"
                        width="100">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="住址"
                        prop="addr"
                        width="150">
                </el-table-column>
                <el-table-column
                        align="center"
                        label="所在班级"
                        prop="cname"
                        width="150">
                </el-table-column>
                <el-table-column label="操作"  align="center">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                plain
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                plain
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页导航-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="curPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>

        <!--1. 添加或修改学生对话框-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            {{form}}---
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" style="width:90%" prop="sname">
                    <el-input v-model="form.sname" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth"  style="width:90%" prop="sex">
                    <el-select v-model="form.sex" placeholder="请选择性别" style="width:100%">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth"  style="width:90%" prop="age">
                    <el-input v-model.number="form.age" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth"  style="width:90%" prop="addr">
                    <el-input v-model="form.addr" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth" style="width:90%" prop="cid">
                    <el-select v-model="form.cid" placeholder="请选择班级" style="width:100%">
                        <el-option :label="c.cname" :value="c.cid" v-for="(c,index) in classes" :key="index"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editStudent">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Student",
        data(){
            //1.  自定义校验规则(此时注意：每一个判断都需要一个callback())
            var checkAge = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('年龄不能为空'));
                }else if (!Number.isInteger(value)) { //如果年龄不是整数，就提示
                    callback(new Error('年龄必须是整数.'));
                }else{
                    callback();
                }
            };
            return {
                studentForm:{},
                tableData: [],
                form:{},
                classes:[],
                title:'添加学生',
                dialogFormVisible:false,
                formLabelWidth:'120px',
                curPage:1,      //当前页
                pageSize:5,     //每页大小
                total: 100,       //总记录数
                rules:{
                    sname: [
                        { required: true, message: '请填写学生姓名', trigger: 'blur' }
                    ],
                    sex:[
                        { required: true, message: '请选择学生性别', trigger: 'change' }
                    ],
                    age:[
                        // {required: true,message:'请填写学生年龄',trigger:'blur'},
                        { validator: checkAge, trigger: 'blur' }
                    ],
                    addr:[
                        {required: true,message:'请填写学生住址',trigger:'blur'}
                    ],
                    cid:[
                        {required: true,message:'请选择所在班级',trigger:'change'}
                    ]
                }
            }
        },
        created() {
            // this.findAllStudents();
            // this.handleCurrentChange();
            //1. 查询所有学生
            this.search();
            //2. 查询所有班级
            this.findClasses();
        },
        methods:{
            //1. 查询所有学生
            findAllStudents(){
                this.axios.get("/student/list").then(({data})=>{
                    this.tableData = data.data.students;
                })
            },
            //2. 当前页大小改变时触发的事件回调函数
            handleSizeChange(val) {
                this.pageSize = val;
                //this.handleCurrentChange(this.curPage);
                this.search();
            },
            //3. 当前页改变时触发的事件回调函数
            handleCurrentChange(val=1) {
                this.curPage = val;
               //3.1 当前页大小改变时，异步向后台发送请求(分页查询 )
               //  let url = `/student/findByPage?page=${this.curPage}&pageSize=${this.pageSize}`
               //  this.axios.get(url).then(({data})=>{
               //      // console.log(data);
               //      if(data.code == 20000){
               //          //1.1 更新当前页的记录集合
               //          this.tableData = data.data.rs.rows;
               //          //1.2 更新总记录数
               //          this.total = data.data.rs.total;
               //      }
               //
               //  })
               //3.2 条件查询带分页
               this.search();
            },
            //4. 添加学生对话框界面
            addStudent(){
                //4.1 修改变量，让对话框显示
                this.dialogFormVisible = true;
                //4.2 修改标题
                this.title = "添加学生";
                //4.3 清空原来的form数据
                this.form = {};
            },
            //5. 条件查询带分页
            search(){
                this.axios.post(`/student/search?page=${this.curPage}&pageSize=${this.pageSize}`,this.studentForm).then(({data})=>{
                    if(data.code == 20000){
                        //1.1 更新当前页的记录集合
                        this.tableData = data.data.rs.rows;
                        //1.2 更新总记录数
                        this.total = data.data.rs.total;
                    }
                })
            },
            //6. 查询学生班级
            findClasses(){
              this.axios.get("/classes/findAll").then(({data})=>{
                  this.classes = data.data.classes;
              })
            },
            //7. 编辑学生（添加或修改，关键点：如何区分是添加还是修改？）
            editStudent(){
               //第一部分：确定url地址
               //7.1 定义访问的址
               let url = "/student/add";
               //7.2 根据是否有sid的值，确定是添加还是修改
               if(this.form.sid){
                   url = "/student/update";
               }

               //第二部分：判断表单数据是否校验通过
               this.$refs['ruleForm'].validate(valid=>{
                   let _this = this;
                   // alert(valid);
                   if(valid){       //如果是true,代表表单中所有的控件都验证通过
                       this.axios.post(url,this.form).then(({data})=>{
                           if(data.code == 20000){      //代表后台数据访问成功
                               //2.0 弹出消息框，当消息框显示结束后，才做下面的事情
                               this.$message({
                                   message: `${this.form.sid?'修改学生成功！':'添加学生成功!'}`,
                                   type: 'success',
                                   onClose(){   //提示框消失后，执行的代码
                                       //2.1 重新刷新页面
                                       _this.search();
                                       //2.2 关闭对话框
                                       _this.dialogFormVisible = false;
                                   }
                               });

                           }else{
                               this.$message({
                                   showClose: true,
                                   message: `${this.form.sid?'修改学生失败！':'添加学生失败!'}`,
                                   type: 'error'
                               });
                           }
                       })
                   }
              })
            },
            //8. 修改学生的界面显示
            handleEdit(index, row) {
                //8.1 显示对话框
                this.dialogFormVisible = true;
                //8.2 将当前row的数据添加到对话框中
                this.form = row;
                //8.3 修改标题
                this.title = "修改学生"
            },
            //9. 删除学生
            handleDelete(index, row) {
                let _this = this;
                this.$confirm(`你确定删除${row.sname}吗?`, '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {     //点击了”确定“按钮后，执行删除操作
                    this.axios.get(`/student/delete?sid=${row.sid}`).then(({data})=>{
                        if(data.code == 20000){
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                onClose(){
                                    //2.1 重新刷新页面
                                    _this.search();
                                    //2.2 关闭对话框
                                    _this.dialogFormVisible = false;
                                }
                            });
                        }
                    })
                }).catch(() => {        //点击了”取消“按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        }
    }
</script>

<style scoped>
    .el-pagination{
        text-align: right;
        margin-top: 20px;
    }
    .el-breadcrumb{
        margin-bottom: 20px;
    }
</style>